package graphics;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.MemoryImageSource;

import javax.swing.JPanel;

/** Create an image from a pixel array. * */
class ImagePanel extends JPanel {
	
	private static final long serialVersionUID = 8805461607390138883L;
	Image fImage;
	int fWidth = 0, fHeight = 0;
	int newArr[];

	public ImagePanel(int fPixels[][], int fWidth, int fHeight) {
		init(fPixels, fWidth, fHeight);
	}

	/**
	 * Create an image from a pixel array and MemoryImageSource.
	 * 
	 * Do the image building in this method rather than in a constructor so that
	 * it will know the size of the panel after it has been added to the applet.
	 */
	void init(int fPixels[][], int fWidth, int fHeight) {

		this.setSize(fWidth, fHeight);
		int i = 0;

		// Now create the image from the pixel array.
		newArr = new int[fWidth * fHeight];
		int white = (255 << 24) | (255 << 16) | (255 << 8) | 255;
		for (int x = 0; x < fWidth; ++x)
			for (int y = 0; y < fHeight; y++) {
				newArr[i++] = (fPixels[y][x] == 0) ? white : fPixels[y][x];

			}

		fImage = createImage(new MemoryImageSource(fWidth, fHeight, newArr, 0,
				fWidth));
	} // init

	void overdraw(int fPixels[][], int fWidth, int fHeight) {
		int i = 0;
		for (int x = 0; x < fWidth; ++x)
			for (int y = 0; y < fHeight; y++) {
				int color = (fPixels[y][x] == 0) ? newArr[i] : fPixels[y][x];
				newArr[i++] = color;

			}
		fImage = createImage(new MemoryImageSource(fWidth, fHeight, newArr, 0,
				fWidth));
	}

	/** Paint the image on the panel. * */
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(fImage, 0, 0, this);
	}

} // class ImagePanel
